<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;

class Aliyunsms {

    public static function createClient($accessKeyId, $accessKeySecret) {
        $config = new Config([
            // 您的 AccessKey ID
            "accessKeyId" => $accessKeyId,
            // 您的 AccessKey Secret
            "accessKeySecret" => $accessKeySecret
        ]);
        // 访问的域名
        $config->endpoint = "dysmsapi.aliyuncs.com";
        return new Dysmsapi($config);
    }

    public static function sendAliyunSms($sign, $mobile, $templateCode, $jsonParam) {
        $config_sms = config_item("aliyun_sms");
        $client = self::createClient($config_sms["accessKeyId"], $config_sms["accessKeySecret"]);
        $runtime = new RuntimeOptions([]);

        $sendParam = [
            "signName" => $sign,
            "templateCode" => $templateCode,
            "phoneNumbers" => $mobile,
            "templateParam" => $jsonParam
        ];
        $sendSmsRequest = new SendSmsRequest($sendParam);

        log_message('error', "阿里云->发送短信->发送数据" . jsonEncode($sendParam));
        $sendSmsResponse = $client->sendSmsWithOptions($sendSmsRequest, $runtime);
        $sendSmsResponse = (array) ($sendSmsResponse);
        //print_r($sendSmsResponse);
        log_message('error', "阿里云->发送短信->接收数据" . jsonEncode($sendSmsResponse));

        $status_code = 0;
        $msg = "";
        $data = [];

        if ($sendSmsResponse["statusCode"] == 200) {
            $body = (array) $sendSmsResponse["body"];
            if ($body["code"] == "OK") {
                $status_code = 1;
                $data = $body;
            } else {
                $msg = $body["message"];
            }
        } else {
            $msg = "返回结果异常";
        }

        return [
            "status_code" => $status_code,
            "msg" => $msg,
            "data" => $data,
        ];
    }

}
